package com.turnengine.client.local.location.plugin.grid;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.turnengine.client.local.location.bean.ICoordinateGrid;

public class CoordinateGridSet implements ICoordinateGridSet {

	private static final Logger log = LoggerFactory.getLogger(CoordinateGridSet.class);

	private final int totalLocationCount;
	private final int[] gridElementCount;
	private final int[] gridLocationCount;
	private final ICoordinateGrid[] grids;

	public CoordinateGridSet(List<ICoordinateGrid> gridList) {
		if (gridList.isEmpty()) {
			throw new IllegalArgumentException("gridList is empty");
		}
		final int length = gridList.size();
		this.grids = gridList.toArray(new ICoordinateGrid[gridList.size()]);
		this.gridElementCount = new int[length];
		this.gridLocationCount = new int[length];

		// Element Counts
		int total = 1;
		for (int i = 0; i < length; i++) {
			ICoordinateGrid grid = grids[i];
			log.info("[Grid " + i + "] " + grid);
			gridElementCount[i] = grid.getLength() * grid.getWidth();
			total *= gridElementCount[i];
		}

		// Location Counts
		gridLocationCount[length - 1] = 1;
		for (int i = length - 2; i >= 0; i--) {
			gridLocationCount[i] = gridLocationCount[i + 1] * gridElementCount[i + 1];
		}

		this.totalLocationCount = total;
	}

	public int grids() {
		return grids.length;
	}

	public List<ICoordinateGrid> toList() {
		return Arrays.asList(grids);
	}

	public int getTotalLocations() {
		return totalLocationCount;
	}

	public int getGridElements(int index) {
		if (index == -1) {
			return 1;
		}
		return gridElementCount[index];
	}

	public int getGridLocations(int index) {
		if (index == -1) {
			return totalLocationCount;
		}
		return gridLocationCount[index];
	}

}
